# -*- coding: utf-8 -*-
# name: tiffExtent.py
# description: 得到tiff文件的extent范围，并以json保存在本目录
# 运行之前保证几点:
# 1.本程序先针对指定路径下的文件夹进行扫描，如果该文件夹下有tif文件则生成对应的json文件，一个文件夹一个json文件。
# json文件形式如下：
# [
#     {
#         "name": "440000-V1-A11-001-01_1",
#         "xmax": 45.11,
#         "xmin": 44.11,
#         "ymax": 118.11,
#         "ymin": 117.11
#     },
#     {
#         "name": "440000-V1-A11-001-01_2",
#         "xmax": 45.11,
#         "xmin": 44.11,
#         "ymax": 118.11,
#         "ymin": 117.11
#     },
#     {
#         "name": "440000-V1-A11-001-01_3",
#         "xmax": 45.11,
#         "xmin": 44.11,
#         "ymax": 118.11,
#         "ymin": 117.11
#     }
# ]
# 2.指定__main__下面的dir为根文件路径。路径要用 \\ 或者 /。为了避免大家的麻烦，路径和文件名切勿出现中文！！！
# 3.测试在ArcGIS 10.1下可用
# 4.配置python环境变量 http://www.runoob.com/python/python-install.html
# 5.安装PIL http://www.pythonware.com/products/pil/   Python2.7版本的
import arcpy
import os
import json
from PIL import Image
def fileExtent(filePath):
    # filePath 为tiff的路径，返回tiff文件extent的dict
    # Create a Describe object from the shapefile
    desc = arcpy.Describe(filePath)
    # 先做一个空dictionary 用来存储错误
    dict = {}
    dict["xmax"] = desc.extent.XMax
    dict["xmin"] = desc.extent.XMin
    dict["ymax"] = desc.extent.YMax
    dict["ymin"] = desc.extent.YMin
    dict["spatialReference"] = desc.spatialReference.name
    dict["name"] = desc.baseName
    return dict

def loopFolder(rootPath):
    fanganMap = {}
    #遍历文件夹,key为方案名，value为tif文件名的数组
    for file in os.listdir(rootPath):
        print file
        if os.path.splitext(file)[1] != ".tif":
            continue
        fangan = file[18:20]
        if fanganMap.has_key(fangan) == False:
            fanganMap[fangan] = []
        fanganMap[fangan].append(file)
    for key in fanganMap.keys():
        tifArray = fanganMap[key]
        folder = os.path.join(rootPath,key)
        if os.path.exists(folder) == False:
            os.mkdir(folder)
        for tif in tifArray:
            png = os.path.splitext(tif)[0]+".png"
            tifPath = os.path.join(rootPath,tif)
            pngPath = os.path.join(rootPath,key,png)
            tif2png(tifPath,pngPath)
        extentArray = []
        for tif in tifArray:
            tifPath = os.path.join(rootPath, tif)
            extentArray.append(fileExtent(tifPath))  # 生成json
        jsonPath = os.path.join(rootPath,key, "extent.json")
        fp = open(jsonPath,"w")
        fp.writelines(json.dumps(extentArray, sort_keys=True, indent=4))
        fp.close()
    print "have a nice day!"
    #end

def tif2png(tifPath,pngPath):
    # 根据tif图像值，转换为颜色的png
    im = Image.open(tifPath)
    imsize = im.size
    outIm = Image.new("RGBA",imsize)
    # outIm.convert("RGBA")
    pix = im.load()
    outPix = outIm.load()
    for i in range(imsize[0]):
        for j in range(imsize[1]):
            if pix[i,j] == 0:
                pass
            elif pix[i,j] < 0.5:
                outPix[i,j] = (188,211,255,204)
            elif pix[i,j] >= 0.5 and pix[i,j] < 1:
                outPix[i, j] = (155,184,240,204)
            elif pix[i,j] >= 1 and pix[i,j] < 2:
                outPix[i, j] = (123,146,224,204)
            elif pix[i, j] >= 2 and pix[i, j] < 3:
                outPix[i, j] = (74,96,233, 204)
            elif pix[i, j] >= 3:
                outPix[i, j] = (3,74,214, 204)
    outIm.save(pngPath)

if __name__ == '__main__':
    # dir1 = u"D:/洪水过程"
    loopFolder(u"D:/洪水过程/新建文件夹")
    #dir1 = u"D:/洪水过程/440000-V1-A11-001-01_1.tif"
    #tif2png(dir1)
